import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login' //非延迟加载
import servicesApi from '@/services/servicesApi';
import storageService from '@/store/storage';
import { isURL } from '@/utils/validate'
import { clearLoginInfo } from '@/utils';
Vue.use(VueRouter)

// 页面路由(独立页面)静态路由
export const pageRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login'),
    name: 'login',
    meta: { title: '登录' }
  },
  {
    path: '/404',
    component: () => import('@/components/404'),
    name: '404',
    meta: { title: '404未找到' },
    beforeEnter(to, from, next) {//路由独享的守卫
      // 拦截处理特殊业务场景
      // 如果, 重定向路由包含__双下划线, 为临时添加路由
      if (/__.*/.test(to.redirectedFrom)) {
        return next(to.redirectedFrom.replace(/__.*/, ''))
      }
      next()
    }
  },
  {
    path: '/forget-password',
    name: 'forget-password',
    component: () => import('@/views/forget-password'),
    meta: { title: '重置密码' }
  },
]

// 模块路由(基于主入口布局页面)
export const moduleRoutes = {
  path: '/',
  component: () => import('@/views/components/Main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口布局' },
  children: [
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    {
      path: '/home',
      component: () => import('@/views/components/Home'), 
      name: 'home',
      meta: { title: '首页', isTab: true },
      // beforeEnter(to, from, next) {
      //   // console.log('------------路由独享守卫--------')
      //   let token = storageService.getToken()
      //   if (!token) {
      //     clearLoginInfo
      //     next({ name: 'login' })
      //   }
      //   next()
      // }
    },
    { path: '/Theme', component: () => import('@/components/Theme'), name: 'Theme', meta: { title: '主题' } },
    // { path: '/demo-echarts', component: _import('demo/echarts'), name: 'demo-echarts', meta: { title: 'demo-echarts', isTab: true } },
    // { path: '/demo-ueditor', component: _import('demo/ueditor'), name: 'demo-ueditor', meta: { title: 'demo-ueditor', isTab: true } }
  ],
  
}

export function addDynamicRoute(routeParams, router) {
  // 组装路由名称, 并判断是否已添加, 如是: 则直接跳转
  let routeName = routeParams.routeName
  let dynamicRoute = window.SITE_CONFIG['dynamicRoutes'].filter(item => item.name === routeName)[0]
  if (dynamicRoute) {
    return router.push({ name: routeName, params: routeParams.params })
  }
  // 否则: 添加并全局变量保存, 再跳转
  dynamicRoute = {
    path: routeName,
    component: () => import(`@/views/${routeParams.path}`),
    name: routeName,
    meta: {
      ...window.SITE_CONFIG['contentTabDefault'],
      menuId: routeParams.menuId,
      title: `${routeParams.title}`
    }
  }
  router.addRoutes([
    {
      ...moduleRoutes,
      name: `main-dynamic__${dynamicRoute.name}`,
      children: [dynamicRoute]
    }
  ])
  window.SITE_CONFIG['dynamicRoutes'].push(dynamicRoute)
  router.push({ name: dynamicRoute.name, params: routeParams.params })
}

const router = new VueRouter({
  mode: 'history', // 去掉URL中的#
  scrollBehavior: () => { return { y: 0 } }, //新页面滚动到顶部
  routes: pageRoutes.concat(moduleRoutes),
})
// // console.log('=========router========================')
// // console.log(router)

router.onError((error) => { //Vue项目中出现Loading chunk {n} failed问题的解决方法
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  if (isChunkLoadFailed) {
    // window.location.reload();
    router.replace(router.history.pending.fullPath);
  } else {
    // console.log(error)
  }
});

router.beforeEach((to, from, next) => { //前置守卫
  // console.log('from=%s,%s', from.path, from.name)
  // console.log('to=%s,%s', to.path, to.name)

  // 添加动态(菜单)路由
  // 已添加或者当前路由为页面路由, 可直接访问
  if (window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] || fnCurrentRouteIsPageRoute(to, pageRoutes)) {
    if (window.SITE_CONFIG['dynamicMenuRoutesHasAdded']) {
      // console.log('========已添加为动态路由===========')
    } else {
      // console.log('========当前路由为静态路由===========')
    }
    return next()
  }
  // if (!storageService.getToken()) { //已登录,有token
  //   // console.log('========无token===========') //没登陆
  //   next({ name: 'login' })
  //   // // console.log(storageService.getToken())
  //   // return next()
  // }
  // console.log('========动态添加路由===========')

  // 获取字典列表, 添加并全局变量保存
  servicesApi.getAllDict().then(res => {
    if (res.data.code !== 200) {
    return this.$message.error(res.data.msg)
  }
    window.SITE_CONFIG['dictList'] = res.data.data
    // console.log('数据字典%o', window.SITE_CONFIG['dictList'])
  })

  // 获取菜单列表, 添加并全局变量保存
  servicesApi.getMenuNav().then(res => {
    // console.log('动态菜单%o', res.data.data)
    if (res.data.data.length ==0 || res.data.code !== 200) {
      //判空写在||前面 ,数组判空不能直接和null比较
      // console.log('********菜单列表请求失败*********')
      this.$message.error(res.data.msg)
      return next({ name: 'login' })
    }
    window.SITE_CONFIG['menuList'] = res.data.data
    fnAddDynamicMenuRoutes(window.SITE_CONFIG['menuList'])
    next({ ...to, replace: true })
  }).catch(() => {
    next({ name: 'login' })
  })
})

router.afterEach((to) => { // 全局后置钩子
  document.title = to.meta.title //设置页面标题
})

/**
 * 判断当前路由是否为页面路由（静态路由）
 * @param {*} route 当前路由
 * @param {*} pageRoutes 页面路由
 */
function fnCurrentRouteIsPageRoute(route, pageRoutes = []) {
  let temp = []
  for (let i = 0; i < pageRoutes.length; i++) {
    if (route.path === pageRoutes[i].path) { //静态路由里判断
      return true
    }
    if (pageRoutes[i].children && pageRoutes[i].children.length >= 1) { //依次存入静态路由的所有子路由
      temp = temp.concat(pageRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteIsPageRoute(route, temp) : false //在静态路由的所有子路由里判断
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  let temp = []
  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children)
      continue
    }
    // // console.log('========单路由组装=======')
    // 组装路由
    let route = {
      path: '',
      component: null,
      name: '',
      meta: {
        ...window.SITE_CONFIG['contentTabDefault'],
        menuId: menuList[i].permId.toString(),
        title: menuList[i].permsName
      }
    }
    // // console.log(route)
    // routes.push(route)

    // eslint-disable-next-line
    let URL = (menuList[i].path || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量
    if (isURL(URL)) {
      route['path'] = route['name'] = `i-${menuList[i].permId.toString()}`
      route['meta']['iframeURL'] = URL
    } else {
      URL = URL.replace(/^\//, '').replace(/_/g, '-')
      route['path'] = route['name'] = URL.replace(/\//g, '-')
      route['component'] = () => import(`@/views/${URL}`)
    }
    // // console.log('URL=%s', URL)
    // // console.log('path=%s', route.path)
    // // console.log(route.meta)
    // // console.log('name=%s', route.name)
    // // console.log('component=%s\n', route.component)
    routes.push(route)
  }
  if (temp.length >= 1) { //递归添加所有动态路由的后代路由
    // // console.log('========所有子路由组装=======')
    return fnAddDynamicMenuRoutes(temp, routes)
  }
  // 添加路由
  router.addRoutes([
    {
      ...moduleRoutes,
      name: 'main-dynamic-menu',
      children: routes
    },
    { path: '*', redirect: { name: '404' } }
  ])
  // console.log(routes)
  window.SITE_CONFIG['dynamicMenuRoutes'] = routes
  // // console.log('====动态菜单路由===')
  // // console.log(window.SITE_CONFIG['dynamicMenuRoutes'])
  window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = true
}

export default router 